package com.doubao.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.doubao.common.result.Result;
import com.doubao.user.dto.request.UserApiKeyRequest;
import com.doubao.user.dto.response.UserInfoResponse;
import com.doubao.user.entity.UserApiKey;
import com.doubao.user.service.UserApiKeyService;
import com.doubao.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户API密钥控制器
 */
@RestController
@RequestMapping("/api-key")
@RequiredArgsConstructor
@Tag(name = "用户API密钥管理", description = "用户API密钥相关接口")
public class UserApiKeyController {

    private final UserService userService;
    private final UserApiKeyService userApiKeyService;

    /**
     * 添加API密钥
     */
    @PostMapping("/add")
    @Operation(summary = "添加API密钥", description = "添加用户API密钥")
    public Result<Void> addApiKey(@Valid @RequestBody UserApiKeyRequest request) {
        UserInfoResponse userInfo = userService.getCurrentUserInfo();
        return userApiKeyService.addApiKey(userInfo.getId(), request);
    }

    /**
     * 更新API密钥
     */
    @PutMapping("/update/{id}")
    @Operation(summary = "更新API密钥", description = "更新用户API密钥信息")
    public Result<Void> updateApiKey(@PathVariable("id") Long keyId, @Valid @RequestBody UserApiKeyRequest request) {
        // 验证当前用户是否有权限操作此API密钥
        UserInfoResponse userInfo = userService.getCurrentUserInfo();
        UserApiKey apiKey = userApiKeyService.getApiKeyById(keyId);

        if (apiKey == null) {
            return Result.failed("API密钥不存在");
        }

        if (!apiKey.getUserId().equals(userInfo.getId())) {
            return Result.failed("无权操作该API密钥");
        }

        return userApiKeyService.updateApiKey(keyId, request);
    }

    /**
     * 删除API密钥
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除API密钥", description = "删除用户API密钥")
    public Result<Void> deleteApiKey(@PathVariable("id") Long keyId) {
        // 验证当前用户是否有权限操作此API密钥
        UserInfoResponse userInfo = userService.getCurrentUserInfo();
        UserApiKey apiKey = userApiKeyService.getApiKeyById(keyId);

        if (apiKey == null) {
            return Result.failed("API密钥不存在");
        }

        if (!apiKey.getUserId().equals(userInfo.getId())) {
            return Result.failed("无权操作该API密钥");
        }

        return userApiKeyService.deleteApiKey(keyId);
    }

    /**
     * 获取用户API密钥列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取用户API密钥列表", description = "获取当前登录用户的API密钥列表")
    public Result<List<UserApiKey>> getUserApiKeys() {
        UserInfoResponse userInfo = userService.getCurrentUserInfo();
        List<UserApiKey> apiKeys = userApiKeyService.getUserApiKeys(userInfo.getId());
        return Result.success(apiKeys);
    }

    /**
     * 分页获取用户API密钥列表
     */
    @GetMapping("/page")
    @Operation(summary = "分页获取用户API密钥列表", description = "分页获取当前登录用户的API密钥列表")
    public Result<IPage<UserApiKey>> getUserApiKeysPage(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        UserInfoResponse userInfo = userService.getCurrentUserInfo();
        IPage<UserApiKey> apiKeys = userApiKeyService.getUserApiKeysPage(userInfo.getId(), page, size);
        return Result.success(apiKeys);
    }

    /**
     * 获取API密钥详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取API密钥详情", description = "获取指定API密钥的详细信息")
    public Result<UserApiKey> getApiKeyDetail(@PathVariable("id") Long keyId) {
        // 验证当前用户是否有权限查看此API密钥
        UserInfoResponse userInfo = userService.getCurrentUserInfo();
        UserApiKey apiKey = userApiKeyService.getApiKeyById(keyId);

        if (apiKey == null) {
            return Result.failed("API密钥不存在");
        }

        if (!apiKey.getUserId().equals(userInfo.getId())) {
            return Result.failed("无权查看该API密钥");
        }

        return Result.success(apiKey);
    }

    /**
     * 更新API密钥激活状态
     */
    @PutMapping("/active/{id}/{status}")
    @Operation(summary = "更新API密钥激活状态", description = "启用或禁用指定的API密钥")
    public Result<Void> updateActiveStatus(
            @PathVariable("id") Long keyId,
            @PathVariable("status") Integer status) {
        // 验证当前用户是否有权限操作此API密钥
        UserInfoResponse userInfo = userService.getCurrentUserInfo();
        UserApiKey apiKey = userApiKeyService.getApiKeyById(keyId);

        if (apiKey == null) {
            return Result.failed("API密钥不存在");
        }

        if (!apiKey.getUserId().equals(userInfo.getId())) {
            return Result.failed("无权操作该API密钥");
        }

        return userApiKeyService.updateActiveStatus(keyId, status);
    }

    /**
     * 重置API密钥已用配额
     */
    @PutMapping("/reset-quota/{id}")
    @Operation(summary = "重置API密钥已用配额", description = "将指定API密钥的已用配额重置为0")
    public Result<Void> resetQuotaUsed(@PathVariable("id") Long keyId) {
        // 验证当前用户是否有权限操作此API密钥
        UserInfoResponse userInfo = userService.getCurrentUserInfo();
        UserApiKey apiKey = userApiKeyService.getApiKeyById(keyId);

        if (apiKey == null) {
            return Result.failed("API密钥不存在");
        }

        if (!apiKey.getUserId().equals(userInfo.getId())) {
            return Result.failed("无权操作该API密钥");
        }

        return userApiKeyService.resetQuotaUsed(keyId);
    }

    /**
     * 更新API密钥配额限制
     */
    @PutMapping("/quota-limit/{id}/{limit}")
    @Operation(summary = "更新API密钥配额限制", description = "设置指定API密钥的配额限制")
    public Result<Void> updateQuotaLimit(
            @PathVariable("id") Long keyId,
            @PathVariable("limit") Long limit) {
        // 验证当前用户是否有权限操作此API密钥
        UserInfoResponse userInfo = userService.getCurrentUserInfo();
        UserApiKey apiKey = userApiKeyService.getApiKeyById(keyId);

        if (apiKey == null) {
            return Result.failed("API密钥不存在");
        }

        if (!apiKey.getUserId().equals(userInfo.getId())) {
            return Result.failed("无权操作该API密钥");
        }

        return userApiKeyService.updateQuotaLimit(keyId, limit);
    }

    /**
     * 验证API密钥是否有效
     */
    @PostMapping("/validate")
    @Operation(summary = "验证API密钥是否有效", description = "验证指定提供商的API密钥是否有效")
    public Result<Boolean> validateApiKey(
            @RequestParam("provider") String provider,
            @RequestParam("key") String key) {
        return userApiKeyService.validateApiKey(provider, key);
    }
}